<template>
  <el-card>
    <template #header>
      <div>
        <span>学生列表</span>&nbsp;&nbsp;&nbsp;&nbsp;
        <el-button class="button" size="small" @click="onAdd()" type="primary">
          输入成绩信息
        </el-button>
      </div>
    </template>
    <!-- 展示学生信息列表 -->
    <el-table :data="todolist" :stripe="true" style="width: 100%">
      <el-table-column type="index" label="" align="center" width="60">
      </el-table-column>
      <el-table-column prop="stuName" label="姓名"> </el-table-column>
      <el-table-column prop="stuScore" label="分数"> </el-table-column>
      <el-table-column prop="stuTest" label="考试科目"> </el-table-column>
      <el-table-column prop="stuDate" label="考试时间">
        <template #default="scope">
          <span v-text="formatDate(scope.row.stuDate)"></span>
        </template>
      </el-table-column>

      <el-table-column prop="" label="操作" align="center">
        <template #default="scope">
          <el-button
            size="small"
            plain
            type="primary"
            @click="onEdit(scope.$index)"
            >修改</el-button
          >
          <el-button
            size="small"
            plain
            type="danger"
            @click="onDelete(scope.$index)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <el-pagination
     v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[2, 5, 10, 20]"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!--添加学生对话框-->
    <el-dialog
      width="40%"
      v-model="dialog.show"
      :title="dialog.title"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :modal-append-to-body="false"
      @close="closeDialog"
    >
      <el-form :model="mymodel" :rules="myrule" ref="myform">
        <el-form-item label="姓名" required prop="stuName">
          <el-col :span="15">
            <el-input type="text" v-model="mymodel.stuName"> </el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="分数" required prop="stuScore">
          <el-col :span="15">
            <el-input type="text" v-model="mymodel.stuScore"> </el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="考试科目" required prop="stuTest">
          <el-col :span="15">
            <el-input type="text" v-model="mymodel.stuTest"> </el-input>
          </el-col>
        </el-form-item>

        <el-form-item label="考试时间" required prop="stuDate">
          <el-col :span="15">
            <el-date-picker
              v-model="mymodel.stuDate"
              type="date"
              placeholder="选择日期"
            >
            </el-date-picker>
          </el-col>
        </el-form-item>
        <el-form-item> </el-form-item>
      </el-form>
      <div>
        <el-button type="primary" @click="onSave('myform')">保 存</el-button>
        <el-button @click="dialog.show = false">取 消</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>
<script>
import http from "../../util/http.js";

import { ElMessage, ElPagination } from "element-plus";
export default {
  name: "StuList",
  components: {
    ElPagination,
  },
  // 定义响应式数据
  data: function () {
    return {
      todolist: [],
      mymodel: {
        id: "",
        stuName: "",
        stuScore: "",
        stuTest: "",
        stuDate: "",
        currentStatus: 0,
      },
      myrule: {
        stuName: [{ required: true, message: "名称不能为空", trigger: "blur" }],
        stuScore: [
          { required: true, message: "分数不能为空", trigger: "blur" },
        ],
        stuTest: [
          { required: true, message: "考试科目不能为空", trigger: "blur" },
        ],
        stuDate: [{ required: true, message: "日期不能为空", trigger: "blur" }],
      },
      dialog: {
        title: "",
        show: false,
        option: "",
      },
      selectedIndex: -1,
      userInfo: {},
      total: 0,
      currentPage: 1,
      pageSize: 2,
    };
  },
  //生命周期函数
  mounted() {
    this.initTable();
  },
  //定义各种函数

  methods: {
    //初始化表格
    initTable() {
      this.userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
      
      http.get("/todo").then((res) => {
        //更新表格
        this.total = res.data.length;
      });
      http.get(`/todo?_page=${this.currentPage}&_limit=${this.pageSize}`).then((res) => {
        //更新表格
        this.todolist = res.data;
      });
    },
    //打开添加任务对话框
    onAdd: function () {
      //清空表单旧数据
      this.mymodel = {
        id: "",
        stuName: "",
        stuScore: "",
        stuTest: "",
        stuDate: "",
        currentStatus: 0,
      };
      //打开对话框
      this.dialog = {
        title: "添加任务",
        show: true,
        option: "add",
      };
    },
    //打开修改任务对话框
    onEdit: function (index) {
      //回填表单
      let item = this.todolist[index];
      this.mymodel = { ...item };
      //临时保存选中的索引
      this.selectedIndex = index;
      //打开对话框
      this.dialog = {
        title: "修改任务",
        show: true,
        option: "edit",
      };
    },
    //保存
    onSave(formName) {
      if (this.dialog.option == "add") {
        //添加保存
        this.$refs[formName].validate((valid) => {
          if (valid) {
            console.log(this.mymodel);
            http.post("/todo", this.mymodel).then((res) => {
              //console.log(res.data)
              ElMessage({
                message: "添加成功！",
                type: "success",
              });
              //更新表格
              //this.todolist.push(res.data)
              this.initTable();
              //清空表单旧数据
              this.mymodel = {
                id: "",
                stuName: "",
                stuScore: "",
                stuTest: "",
                stuDate: "",
                currentStatus: 0,
              };
              //关闭对话框
              this.dialog = {
                title: "",
                show: false,
                option: "",
              };
            });
          }
        });
      } else if (this.dialog.option == "edit") {
        console.log(this.mymodel);
        //修改保存
        this.$refs[formName].validate((valid) => {
          if (valid) {
            //json-server更新数据需要带一个路径变量id，才能修改
            //格式如：http://localhost:3000/todo/1001
            http.put("/todo/" + this.mymodel.id, this.mymodel).then((res) => {
              ElMessage({
                message: "修改成功！",
                type: "success",
              });
              //更新页面
              this.initTable();
              //清空表单旧数据
              this.mymodel = {
                id: "",
                stuName: "",
                stuScore: "",
                stuTest: "",
                stuDate: "",
                currentStatus: 0,
              };
              //关闭对话框
              this.dialog = {
                title: "",
                show: false,
                option: "",
              };
            });
          }
        });
      }
    },
    //删除任务
    onDelete: function (index) {
      http.delete("/todo/" + this.todolist[index].id).then((res) => {
        if (res.status == "200") {
          ElMessage("删除成功！");
         this.initTable()
        } else {
          ElMessage("删除失败！");
        }
      });
    },
    //时间格式化成中国时间
    formatDate: function (stuDate) {
      let date = new Date(stuDate);
      let seperator = "-";
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let strDate = date.getDate();
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
      }
      let currentdate = year + seperator + month + seperator + strDate;
      return currentdate;
    },
    closeDialog() {
      this.$refs.myform.clearValidate();
      this.dialog = {
        title: "",
        show: false,
        option: "",
      };
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.initTable();
    },
    handleCurrentChange(val) {
      console.log("当前页: ", val);
      this.currentPage = val
      this.initTable();
    }
  },
};
</script>
<style scoped></style>
